package com.ht.medicaltreatment.utils

import android.annotation.SuppressLint
import android.hardware.UHFDevice
import android.os.Build
import android.os.SystemClock
import com.android.hfread.HfData
import com.android.hfread.MyService
import com.android.hfread.Util
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ServiceUtils
import com.blankj.utilcode.util.ToastUtils
import com.gym.baselib.BaseApplication
import com.gym.baselib.utils.runOnMain
import com.gym.baselib.utils.runOnThread
import com.rscja.deviceapi.RFIDWithUHFUART
import com.xgst.lib.utils.TimeUtils

/**
 * 扫描
 */
object ScanUtils {
    private val isV9100 = Build.MODEL == "V9100"
    @SuppressLint("StaticFieldLeak")
    private var mReader:RFIDWithUHFUART? = null
    private var mUHFDevice:UHFDevice? = null
    private var onScanResult:(String) -> Unit = {}
    private var isStart = false
    private val scanList:MutableSet<String> = mutableSetOf()
    private var mIsFilter = false
    private var isInit = false
    private var speed = 19200
    private var mType = 0
    private var mWorking = false
    private var mHFWorking = false
    private var state: Byte = 0
    //private var mHFDevice:HFDevice? = null

    fun init(isFilter:Boolean = true,onInitResult:(Boolean)->Unit = {}){
        if(isInit){
            onInitResult(true)
            return
        }
        mIsFilter = isFilter
        when(Build.MODEL){
            "V9100" -> {
                ServiceUtils.startService(MyService::class.java)
                mUHFDevice = UHFDevice(BaseApplication.context)
                mUHFDevice!!.UhfOpen()
                runOnThread {
                    SystemClock.sleep(1000)
                    val result =
                        HfData.reader.OpenReader(speed, mUHFDevice!!.SerialDev(), mType, 1, null)
                    if (result == 0) {
                        LogUtils.i("扫描器初始化成功")
                        isInit = true
                        runOnMain { onInitResult(true) }
                    } else {
                        LogUtils.i("V9100 打开失败 $result")
                        ToastUtils.showShort("V9100 打开失败 $result")
                        isInit = false
                        runOnMain { onInitResult(false) }
                    }
                }
            }

            "C72" -> {
                try {
                    mReader = RFIDWithUHFUART.getInstance()
                    runOnThread {
                        val result = mReader?.init()
                        isInit = result?:false
                        runOnMain { onInitResult(isInit) }
                        LogUtils.i("超高频初始化成功: $isInit")
                    }
                }catch (e:Exception){
                    isInit = false
                    onInitResult(false)
                    runOnMain { onInitResult(false) }
                    LogUtils.i("超高频初始化失败: ${e.message}")
                }
            }

            /*"JZ V9000S" -> {
                if(mHFDevice != null && mHFDevice!!.isConnect){
                    onInitResult(true)
                    return
                }
                mHFDevice = HFDevice(BaseApplication.context)
                mHFDevice?.apply {
                    PowerOn()
                    setTriggerkey(0)
                    DownTimeUtils.delayedTask{
                        if(isConnect){
                            if(mHFDevice!!.OpenReader() == 0){
                                SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
                                LogUtils.i("设备启动成功")
                                isInit = true
                                onInitResult(true)
                            }else{
                                LogUtils.i("设备启动失败")
                                onInitResult(false)
                                isInit = false
                            }
                        }else{
                            LogUtils.i("设备连接失败")
                            isInit = false
                            onInitResult(false)
                        }
                    }
                }
            }*/

            else -> {
                LogUtils.i("未知设备")
            }
        }
    }

    fun open(result:(String)->Unit){
        LogUtils.i("打开设备失败: $isInit")
        if(!isInit){
            ToastUtils.showShort("打开设备失败")
            LogUtils.file("打开设备识别，初始化失败或者没有调用init方法")
            return
        }
        scanList.clear()
        onScanResult = result
        if(Build.MODEL == "V9100"){
            mWorking = true
            state = 0x06
            SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
            runOnThread {
                while (mWorking){
                    inventoryTag()
                }
            }
        }else if(mReader != null){
            if(mReader?.startInventoryTag() == true){
                isStart = true
                runOnThread {
                    while (isStart){
                        val res = mReader?.readTagFromBuffer()
                        if(res == null || res.epc == null ){
                            continue
                        }
                        if(mIsFilter && scanList.contains(res.epc)){
                            continue
                        }
                        val uid = res.epc
                        //扫描记录  用来过滤
                        scanList += uid
                        runOnMain {
                            onScanResult(uid)
                        }
                    }
                }
            }else{
                LogUtils.file("UHF开启失败")
                ToastUtils.showShort("UHF开启失败")
                mReader?.stopInventory()
            }
        }/*else if(Build.MODEL == "JZ V9000S" && mHFDevice != null){
            runOnThread {
                mHFWorking = true
                while (mHFWorking){
                    startRead()
                }
            }
        }*/else{
            LogUtils.i("未知设备")
        }
    }

/*    private fun startRead() {
        var state = 0x06.toByte()
        var fCmdRet: Int
        do {
            val UID = ByteArray(25600)
            val CardNum = IntArray(1)
            CardNum[0] = 0
            fCmdRet = mHFDevice!!.Inventory(state, UID, CardNum)
            if (CardNum[0] > 0) {
                for (m in 0 until CardNum[0]) {
                    val daw = ByteArray(9)
                    System.arraycopy(UID, m * 9, daw, 0, 9)
                    val uidStr: String = mHFDevice!!.bytesToHexString(daw, 1, 9)
                    if(uidStr == ""){
                        continue
                    }
                    LogUtils.i("扫码： "+uidStr)
                    *//*var uid = ""
                    if(uidStr.length != 8){
                        uid = UIDUitls.sort(uidStr)
                    }
                    if(mIsFilter && scanList.contains(uid)){
                        continue
                    }
                    scanList += uid
                    runOnMain {
                        onScanResult(uid)
                    }*//*
                }
            }
            state = 0x02.toByte()
        } while (fCmdRet != 0x0E)
    }*/

    private fun inventoryTag() {
        var fCmdRet:Int
        do {
            val UID = ByteArray(25600)
            val CardNum = IntArray(1)
            CardNum[0] = 0
            fCmdRet = HfData.reader.Inventory(state, UID, CardNum)
            if (CardNum[0] > 0) {
                for (m in 0 until CardNum[0]) {
                    val daw = ByteArray(9)
                    System.arraycopy(UID, m * 9, daw, 0, 9)
                    val uidStr = Util.bytesToHexString(daw, 1, 9).trim()
                    if(uidStr == ""){
                        continue
                    }
                    var uid = ""
                    if(uidStr.length != 8){
                        uid = UIDUitls.sort(uidStr)
                    }
                    if(mIsFilter && scanList.contains(uid)){
                        continue
                    }
                    scanList += uid
                    runOnMain {
                        onScanResult(uid)
                    }
                }
            }
            state = 0x02.toByte()
        } while (fCmdRet != 0x0E)
    }

    /**
     * 移除已扫描的试管UID记录
     */
    fun reset(){
        scanList.clear()
    }

    /**
     * 3秒后，移除指定的UID记录
     */
    fun resetItem(uid:String){
        TimeUtils.countDownOneTime(3000,{
            scanList.remove(uid)
        })
    }

    fun close(){
        if(isV9100){
            if(mWorking){
                mWorking = false
            }
        }else if(mReader != null){
            if(isStart){
                isStart = false
                mReader?.stopInventory()
            }
        }else if(Build.MODEL == "JZ V9000S"){
            if(mHFWorking){
                mHFWorking = false
            }
        }
    }

    fun onDestroy(){
        if(isV9100){
            if(mWorking){
                mWorking = false
            }
        }
    }
}